import java.util.Arrays;
//创建大根堆
public class Heap {
    private int[] elem;
    private int usedSize;

    public Heap(int[] elem) {
        this.elem = elem;
        usedSize = elem.length;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    //创建堆
    public void createHeap() {
        for (int parent = (this.usedSize-1-1)/2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    //向下调整
    public void shiftDown(int parent, int usedSize) {
        int child = parent * 2 + 1;
        while (child < usedSize) {
            //是否有右节点
            if (child+1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                //父节点下标移动到被交换后的子节点位置
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    //添加
    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[usedSize] = val;
        shifUp(usedSize);
        usedSize++;
    }

    public void shifUp(int child) {
        int parent = (child-1)/2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            } else {
                break;
            }
        }
    }

    public void poll() {
        //交换栈顶元素和最后一个元素
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        shiftDown(0,usedSize-1);
        usedSize--;
    }



}
